import AMap from "AMap";
import { Toast } from "vant";
export default {
  data() {
    return {
      count: 3,
      max_count: 3,
      name: "",
      phone: "",
      time: "2023-2-22",
      fileList: [],
      fileListVideo: [],
      locationTitle: "",
      video_path: [],
      images: [],
      address_title: "",
      form_id: "",
      form_cluster: [],
      text: "",
      message:"",
      lat: "",
      lng: "",
      show: false,
      currentDate: new Date(),
      district: district, // 地址本地数据
      detail:'',
      addressShow:false,
    }
  },
  activated() {
    this.form_id = this.$route.query.form_id;
    let date = new Date();
    let year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate();
    this.time = `${year}-${month}-${day}`;
    this.getData();
    if (JSON.parse(localStorage.getItem('myLocation'))) {
      let _myLocation = JSON.parse(localStorage.getItem('myLocation'));
      this.lng = _myLocation.point.lng;
      this.lat = _myLocation.point.lat;
      this.getAmap(_myLocation.city_name, _myLocation.point.lng, _myLocation.point.lat);
    }
  },
  methods: {
    // 地址回调
    addressCallback(obj) {
      this.address_title = obj.itemName1 + "-" + obj.itemName2 + "-" + obj.itemName3;
    },
    beforeDelete(file, detail) {
      this.images.splice(detail.index, 1);
      return true;
    },
    cancel() {
      this.show = false;
    },
    confirm(date) {
      let year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate();
      this.time = `${year}-${month}-${day}`;
      this.show = false;
    },
    show_popup() {
      this.show = true;
    },
    submit() {
      let json = {
        form_id: this.form_id,
        name: this.name,
        mobile: this.phone,
        date:this.time,
        area: this.address_title,
        rows: this.message,
        images: this.images,
        videos: this.video_path,
        coordinate: {
          longitude: this.lng,
          latitude: this.lat,
          address: this.locationTitle,
        }
      }

      if(this.form_cluster[1].required && !this.phone){
        return this.$toast('请输入'+this.form_cluster[1].title);
      }else if(this.form_cluster[5].required&& !this.message){
        return this.$toast('请输入'+this.form_cluster[5].title);
      }else if(this.form_cluster[7].required&& this.fileListVideo.length==0){
        return this.$toast('请上传'+this.form_cluster[7].title);
      }else if(this.form_cluster[6].required&& this.fileList.length==0){
        return this.$toast('请上传'+this.form_cluster[6].title);
      }else if(this.form_cluster[4].required && !this.time){
        return this.$toast('请选择'+this.form_cluster[4].title);
      }else if(this.form_cluster[3].required && !this.locationTitle){
        return this.$toast('请选择'+this.form_cluster[3].title);
      }else if(this.form_cluster[0].required && !this.name){
        return this.$toast('请输入'+this.form_cluster[0].title);
      }else if(this.form_cluster[2].required && !this.address_title){
        return this.$toast('请选择'+this.form_cluster[2].title);
      }


      $http.post("plugin.shoot-casually.frontend.form-member.submit", json, "").then(({ result, msg }) => {
        this.$toast(msg);
        if (result) {
          this.$router.push(this.fun.getUrl("random_shot_list"))
        }
      })
    },
    uploadAudioM(file) {
      console.log(file,"=====");
      //视频上传
      let uploadAudio = this.fun.getRealUrl("upload.uploadPic", {});
      uploadAudio += "upload_type=video";
      let fd = new FormData();
      fd.append("file", file); //进度百分比
      Toast.loading({
        message: '视频正在上传中',
        forbidClick: true,
      });
      axios
        .post(uploadAudio, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          Toast({ message: response.data.msg });
          if (response.data.result === 1) {
            Toast.clear();
            this.video_path.push(response.data.data.img_url);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getAmap(city, lng, lat) {
      AMap.plugin("AMap.Geocoder", () => {
        var geocoder = new AMap.Geocoder({ city });
        geocoder.getAddress([lng, lat], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            console.log(result, "result====");
            // result为对应的地理位置详细信息
            this.locationTitle = result.regeocode.formattedAddress
          }
        })
      })
    },
    del(index) {
      this.fileListVideo.splice(index, 1);
      this.video_path.splice(index, 1)
    },
    select_location() {
      this.$store.commit("setReferer", window.location.href);
      this.$router.push(this.fun.getUrl("o2oLocation_loc", { fromHome: 1 }));
    },
    afterRead(e,flag) {
      console.log(e);
      if (e && e.length) {
        for (let i = 0; i < e.length; i++) {
          this.onRead_1(e[i], flag);
        }
      } else {
        this.onRead_1(e, flag);
      }


    },
    onRead_1(e,flag){
      Toast.loading({
        message: "上传中",
        forbidClick: true
      });
      let fd = new FormData();
      if (flag === true) {
        fd.append("file", e);
      } else {
        fd.append("file", e.file); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      }
      let uploadAudio = this.fun.getRealUrl("upload.uploadPic", {});
      axios
        .post(uploadAudio, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(({ data: { msg, result, data } }) => {
          this.$toast(msg)
          if (result) {
            this.images.push(data.img_url);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    afterReadVideo(e) {
      let url = null,
      file = e.file;
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file); //类型1
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file); //类型2
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file); //类型3
      }

      var audioElement = new Audio(url);
      let result;
      audioElement.muted = true
      audioElement.play().then(() => audioElement.pause())
      audioElement.addEventListener('loadedmetadata', ()=> {
        // 视频时长值的获取要等到这个匿名函数执行完毕才产生
        result = audioElement.duration //得到时长为秒，小数，182.36
        var serce = parseInt(result)
        if (serce > 300) {
          audioElement.muted = false
          Toast('视频不能超过5分钟')
        } else {
          audioElement.muted = false
          this.fileListVideo.push(url);
          this.uploadAudioM(file)
        }
      })

    },
    getData() {
      $http.get("plugin.shoot-casually.frontend.form.show", { form_id: this.form_id }, "").then(({ result, msg, data }) => {
        if (result) {
          let title = data.title;
          this.text = title;
          this.detail = data.detail;
          this.max_count = data.form_cluster[6].count;
          this.fun.setWXTitle(title);
          this.form_cluster = data.form_cluster;
          this.$nextTick(()=>{
            let json ={ title:data.title, imgUrl:data.form_image_url, description:data.describe };
            this.fun.wxShare("",{},json);
          })
        } else {
          this.$toast(msg);
        }
      })
    }
  }
}